package com.atguigu.gmall.common.interceptors;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.utils.UserAuthUtils;
import com.atguigu.gmall.user.vo.UserAuthInfoVo;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;

/**
 * @author:ahang
 * @create:2022-10-19 23:07
 * @Description:
 */
@Component
public class UserHeaderAuthFeignInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        //实现将老请求中的请求头放到请求模板中
        //从共享数据中拿到老请求
//        HttpServletRequest request = CartController.resultMap.get(Thread.currentThread());
//        HttpServletRequest request = CartController.threadLocal.get();
//        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
//        HttpServletRequest request = attributes.getRequest();
//
//        String userId = request.getHeader(RedisConst.User_ID_HEADER);
//        String userTempId = request.getHeader(RedisConst.User_TEMP_ID_HEADER);
        UserAuthInfoVo info = UserAuthUtils.getUserAuthInfo();

        //如果是异步请求就会产生请求头丢失问题
        if(info != null){
            //将用户id和临时id放到请求模板中
            if(info.getUserId() != null){
                requestTemplate.header(RedisConst.User_ID_HEADER,info.getUserId().toString());
            }
            requestTemplate.header(RedisConst.User_TEMP_ID_HEADER,info.getTempId());
        }
    }
}
